<template>
	<div class="liveColumn w944">
		<alert ref="alert"></alert>
		<deleteAlert ref="deleteAlert"></deleteAlert>
		<div class="label_top">
			<button @click="reBack"><i><&nbsp;</i>返回</button>
			<p>{{updateTitle}}</p>
		</div>
		<div class="label_table">
			<div class="el-tabs-report">
				<a class="listOne" @click="newLiveColumn">添加直播</a>
				<a class="listTwo" @click="importDaoChu">导出数据</a>
				<div class="msearch">
					<input placeholder="请输入直播、讲师等关键词……" v-model="search"/>
					<a @click="getTableList"><img src="../../assets/qudaoImg/search.png"/></a>
				</div>
			</div>
			<el-table ref="multipleTable" :data="tableData" border @selection-change="handleSelectionChange">
				<el-table-column label="序号" width="55">
					<template slot-scope="scope">{{ scope.row.sort}}</template>
				</el-table-column>
				<el-table-column prop="name" label="直播名称" width="260"></el-table-column>
				<el-table-column prop="lecturer" label="讲师" width="70"></el-table-column>
				<el-table-column prop="assistant" label="助教" width="70"></el-table-column>
				<el-table-column prop="starttime" label="直播时间" width="160"></el-table-column>
				<el-table-column label="直播状态" width="80">
					<template slot-scope="scope">
						<span v-if="scope.row.liveBroadcastStatus==0">暂无直播</span>
						<span v-if="scope.row.liveBroadcastStatus==1">等待直播</span>
						<span v-if="scope.row.liveBroadcastStatus==2">正在直播</span>
						<span v-if="scope.row.liveBroadcastStatus==3">直播结束</span>
						<span v-if="scope.row.liveBroadcastStatus==4">直播回放</span>
					</template>
				</el-table-column>
				<el-table-column label="直播链接">
					<template slot-scope="scope">
						<el-button @click="live_Url(scope.row)">查看</el-button>
					</template>
				</el-table-column>
				<el-table-column label="直播数据">
					<template slot-scope="scope">
						<el-button @click="live_Data(scope.row)">查看</el-button>
					</template>
				</el-table-column>
				<!--<el-table-column label="满意度调查">
					<template slot-scope="scope">
						<el-button @click="satisfaction(scope.row)">查看</el-button>
					</template>
				</el-table-column>-->
				<el-table-column label="报名管理">
					<template slot-scope="scope">
						<el-button @click="live_sign(scope.row)">查看</el-button>
					</template>
				</el-table-column>
				<el-table-column label="获奖名单">
					<template slot-scope="scope">
						<el-button @click="winners(scope.row)">查看</el-button>
					</template>
				</el-table-column>
				<el-table-column label="回放操作" width="120">
					<template slot-scope="scope" v-if="scope.row.liveBroadcastStatus==4">
						<el-button @click="handleDownload(scope.row)">下载</el-button> 
						<el-button @click="handlePlayback(scope.row)" class="blue">编辑回放</el-button>
					</template>
				</el-table-column>
				<el-table-column label="其他操作" width="120">
					<template slot-scope="scope">
						<el-button @click="handleEdit(scope.row)">编辑</el-button>
						<el-button @click="handleDelete(scope.row)" class="red">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="fenyeMargin">
				<div class="pag_block">
					<el-pagination @current-change="handleCurrentChange" :current-page="currentpage" :page-size="pagesize" layout="prev, pager, next" :total="total"></el-pagination>
				</div>
			</div>
			<!--直播链接查看弹窗-->
			<div class="liveSeen" v-show="liveSeen">
				<p>直播链接</p>
				<a class="liveClose" @click="liveClose()">&#10005;</a>
				<div class="liveSeen_inner">
					<el-tabs v-model="activeName">
					    <el-tab-pane label="讲师" name="first">
					    	<div class="fenleiDiv">
					    		<div class="line">
					    			<span>网页开播链接:</span>
					    			<input type="text" v-model="tip_1_url1"/>
					    		</div>
					    		<div class="line">
					    			<span>启动客户端链接:</span>
					    			<input type="text" v-model="tip_1_url2"/>
					    		</div>
					    		<p>频道号:{{tip_1_ChannelNo}}<i></i>密码/邀请码:{{tip_1_InviteCode}}</p>
					    	</div>
					    </el-tab-pane>
					    <el-tab-pane label="助教" name="second">
					    	<div class="fenleiDiv">
					    		<div class="line">
					    			<span>助教后台链接:</span>
					    			<input type="text" v-model="tip_2_url1"/>
					    		</div>
					    		<p class="clearFix">频道号:{{tip_2_ChannelNo}}<i></i>密码:{{tip_2_InviteCode}}</p>
					    	</div>
					    </el-tab-pane>
					    <el-tab-pane label="观众" name="third">
					    	<div class="fenleiDiv">
						    	<div class="line">
					    			<span>观众观看链接:</span>
					    			<input type="text" v-model="tip_3_url1"/>
					    		</div>
				    		</div>
					    </el-tab-pane>
					</el-tabs>
				</div>
			</div>
			<!--编辑回放-->
			<div class="editPlayBack" v-show="playBackWrap">
				<p><span>直播名称：</span>{{editPlayBackTitle}}</p>
				<div class="editPlayBackLine">
					<span>修改直播名称：</span>
					<input type="text" placeholder="修改直播名称" v-model="liveBroadcastName"/>
				</div>
				<div class="editPlayBackLine">
					<span>上传回放视频：</span>
					<a class="uploadVideoBtn"><input type="file" id="fileUpload" @change="fileChange($event)">选择文件</a>
					<button @click="authUpload" :disabled="uploadDisabled">开始上传</button>
					<span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i>%</span>
				</div>
				<div class="footerButton">
					<a @click="editPlayBackCheckSave">保存</a>
					<a @click="editPlayBackCancel" class="cancel">取消</a>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import axios from 'axios';
	import echarts from 'echarts';
	import alert from '../../components/Alert.vue';
	import deleteAlert from '../../components/deleteAlert.vue';
	export default {
		data() {
			return {
				liveId:'',
				updateTitle:'',
				teacherTitle:'',
				lecturerid:'',
				liveColumn:'',
				search: '',
				tableData: [],
				sort:'',
				pagesize: 15,
				currentpage: 1,
				total: 1,
				videoUrl:'',
				multipleSelection: [],
				deleteType:'delete',
//				查看直播链接
				liveSeen:false,
				activeName: 'first',
				tip_1_url1:'',
				tip_1_url2:'',
				tip_1_ChannelNo:'',
				tip_1_InviteCode:'',
				tip_2_url1:'',
				tip_2_ChannelNo:'',
				tip_2_InviteCode:'',
				tip_3_url1:'', 
				tip_3_Img:'',
//				直播数据
				liveDataWrap:false,
				liveDataTitle:'',
				liveDataTeacher:'',
				liveDataAssistant:'',
//				编辑回放
				editPlayBackTitle:'',
				liveBroadcastName:'',
				playBackWrap:false,
				aliyunVideoId:'',
				
				timeout: '60000',
				partSize: '1048576',
				parallel: '5',
				retryCount: '3',
				retryDuration: '2',
				region: 'cn-shanghai',
				userId: '1585664211304336',
				file: null,
				authProgress: 0,
				uploadDisabled: true,
				resumeDisabled: true,
				pauseDisabled: true,
				uploader: null,
				statusText: ''
			}
		},
		methods: {
			getParams() {
				let that = this;
				this.liveId = this.$route.params.liveId;
				this.updateTitle = this.$route.params.updateTitle;
				this.pathKey = this.$route.params.pathKey;
//				this.courseCompanyid = this.$route.params.courseCompanyid;
//				if(this.pageTypeNum=2){
					this.teacherTitle = this.$route.params.teacherTitle;
					this.lecturerid = this.$route.params.lecturerid;
//				};
//				this.pageTypeNum = this.$route.params.pageTypeNum;
				console.log('liveColumn:',this.$route.params);
			},
			//路由变化刷新缓存
            savemessage() {
                if(this.liveId!=''&&this.updateTitle!=''){
                	var s={
						liveId : this.liveId,
						liveType:this.liveType,
						updateTitle:this.updateTitle,
						pathKey:this.pathKey,
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid 
					}	
					this.$store.commit('SET_LIVE_COLUMN', s);
                	console.log("路由跳转")
                }
            },
			getTableList(){
				let that = this;
				this.$ajax({
					url: this.$root.jifuUrl + "/getCourseLiveBroadcastPage?"+ 'page=' + this.currentpage + '&num=' + this.pagesize + '&courseid=' + this.liveId +'&name='+this.search+'&rootcompanyid='+1,
					method: 'GET',
					data: {},
					success: res => {
						if(res.data.code == 200){
							this.tableData = res.data.data.list;
							this.total=res.data.data.pageParam.items;
							for(var i = 0;i<this.tableData.length;i++){
								this.tableData[i].sort=i+1
							}
						}
					}
				});
			},
			newLiveColumn(){
				this.$router.push({
					name: 'newLiveColumn',
					params: {
						liveId: this.liveId,
						liveType:'liveColumn',
						updateTitleCourse:this.updateTitle,
						pathKey:this.pathKey,
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid
					}
				})
			},
			handleEdit(row) {
				this.$ajax({
					url: this.$root.jifuUrl + "/getCourseLiveBroadcastById?" + 'id=' + row.id,
					method: 'GET',
					data: {},
					success: res => {
						if(res.data.code == 200) {
							this.$router.push({
								name: 'newLiveColumn',
								params: {
									type: 'edit',
									liveId:this.liveId,
									liveType:'liveColumn',
									pathKey:this.pathKey,
									updateTitleCourse:this.updateTitle
								} 
							});
							this.$root.columnToNewLive = res.data.data;
						}
					}
				});
				
			},
			handleDelete(row){
				this.transitionRow = row;
				this.$rootFunction().rootDelete();
			},
			// 批量删除
			handleDeleteAll() {
				this.$rootFunction().rootDeleteAll();
			},
			deleteSubmit() {
				var s={id:this.transitionRow.id,channelId:this.transitionRow.channelId};
				this.$ajax({
					url: this.$root.jifuUrl + "/deleteCourseLiveBroadcast",
					method: 'POST',
					data: this.qs.stringify(s),
					success: res => {
						if(res.data.code == 200) {
							this.$rootFunction().deleteResSuccess();
						}else{
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
					}
				});
			},
			handleDownload(row){
				let s = {
					fileUrl:row.videoUrl,
					fileName:row.name
				};
				if (window.navigator.msSaveBlob) {
		          	try {
		            	window.navigator.msSaveBlob(blob, s.fileName)
		          	}catch (e) {
		            	console.log(e);
		          	}
		        }else {
					var downloadElement = document.createElement('a');
		          	downloadElement.href = s.fileUrl;
		          	downloadElement.target = '_blank';
		          	downloadElement.download = s.fileName; //下载后文件名
		          	document.body.appendChild(downloadElement);
		          	downloadElement.click(); //点击下载
		          	document.body.removeChild(downloadElement); //下载完成移除元素
		          	window.URL.revokeObjectURL(s.fileUrl); //释放掉blob对象
	            };
				var url = s.fileUrl;
			    var xhr = new XMLHttpRequest();
			    xhr.open('get', url,true); 
			    xhr.responseType = "blob"; // 返回类型blob
			    xhr.onload = function() {
			        // 请求完成
			        if(this.status == 200) {
				        var blob = this.response;
				        var href = window.URL.createObjectURL(blob);
	            	}
	        	}
	    		// 发送ajax请求
	    		xhr.send()
			},
			//编辑回放
			handlePlayback(row){
				this.playBackWrap = true;
				this.editPlayBackTitle = row.name;
				this.playBackRow = row;
			},
			editPlayBackCheckSave(){
				let that = this;
				let s = {
					liveBroadcastid:that.playBackRow.id,
					aliyunVideoId:that.aliyunVideoId,
					liveBroadcastName:that.liveBroadcastName,
					channelId:that.playBackRow.channelId
				};
				this.$ajax({
                    url: this.$root.jifuUrl + '/updateVideoIdByLiveBroadcastid',
                    method: 'POST',
                    data: this.qs.stringify(s),
                    success: res => {
                        if(res.data.code == 200) {
							this.playBackWrap = false;
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.go(0);
							},2000) 
                        }else{
							this.playBackWrap = false;
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
                    }
                });
			},
			editPlayBackCancel(){
				this.playBackWrap = false;
			},
			//查看直播链接 start 
			live_Url(row) {
				this.liveSeen = true;
				this.tip_1_url1 = row.webBroadcast;
				this.tip_1_url2 = row.clientBroadcast;
				this.tip_1_ChannelNo = row.channelId;
				this.tip_1_InviteCode = row.lecturerChannelPass;
				
				this.tip_2_url1 = row.assistantBroadcast;
				this.tip_2_ChannelNo = '001' + row.channelId;
				this.tip_2_InviteCode = row.assistantChannelPass;
				
				this.tip_3_url1 = row.userBroadcast;
			},
			liveClose(){
				this.liveSeen = false;
			},
			openUrl(){},
			copyUrl(){},
			winners(row){
				this.savemessage();
				this.$router.push({
					name:'liveWinners',
					params: {
						updateTitle:row.name,
						liveColumnTitle:this.updateTitle,
						liveBroadcastid:row.id,
						pathKey:this.pathKey,
						liveId:this.liveId,
						liveType:'liveColumn',
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid
					}
				})
			},
//			直播数据
			live_Data(row){
				this.savemessage();
				this.$router.push({
					name:'liveDataColumn',
					params: {
						updateTitle:row.name,
						liveColumnTitle:this.updateTitle,
						liveBroadcastid:row.id,
						isBm:row.isSignUp,
						pathKey:this.pathKey,
						liveId:this.liveId,
						liveType:'liveColumn',
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid
					}
				});
			},
			satisfaction(row){
				this.$router.push({
					name:'satisfaction'
				})
			},
			liveDataClose(){
				this.liveDataWrap = false;
			},
			live_sign(row){
				this.savemessage();
				this.$router.push({
					name: 'liveColumnSign',
					params: { 
						courseid:row.id,
						coursewareId: this.liveId,
						courseName:row.name,
						coursewareType:'3-',
						updateTitle:this.updateTitle,
						liveType:'liveColumn',
						pathKey:this.pathKey,
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid
					}
				})
			},
			toggleSelection(rows) {
				if(rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row, !this.allSelect)
					})
					this.allSelect = !this.allSelect;
				}
			},
			handleSelectionChange(val) {
				this.multipleSelection = [];
				val.forEach(row => {
					this.multipleSelection.push(row.id);
				});
			},
			handleCurrentChange(value) {
				this.currentpage = value;
				this.getTableList();
			},
			reBack(){
				this.savemessage();
				console.log('reback:',this.pathKey);
				this.$router.push({
					name: this.pathKey,
					params: {
						updateTitle:this.teacherTitle,
						lecturerid:this.lecturerid,
						teacherTitle:this.teacherTitle,
					}
				})
			},
			importDaoChu(){},
			fileChange(e) {
				this.file = e.target.files[0]
				if(!this.file) {
					alert("请先选择需要上传的文件!")
					return
				}
				var Title = this.file.name
				var userData = '{"Vod":{}}'
				if(this.uploader) {
					this.uploader.stopUpload()
					this.authProgress = 0
					this.statusText = ""
				}
				this.uploader = this.createUploader()
				console.log(userData)
				this.uploader.addFile(this.file, null, null, null, userData)
				this.uploadDisabled = false
				this.pauseDisabled = true
				this.resumeDisabled = true
			},
			authUpload() {
				// 然后调用 startUpload 方法, 开始上传
				if(this.uploader !== null) {
					this.uploader.startUpload()
					this.uploadDisabled = true
					this.pauseDisabled = false
				}
			},
			// 暂停上传
			pauseUpload() {
				if(this.uploader !== null) {
					this.uploader.stopUpload()
					this.resumeDisabled = false
					this.pauseDisabled = true
				}
			},
			// 恢复上传
			resumeUpload() {
				if(this.uploader !== null) {
					this.uploader.startUpload()
					this.resumeDisabled = true
					this.pauseDisabled = false
				}
			},
			createUploader(type) {
				let self = this
				let uploader = new AliyunUpload.Vod({
					timeout: self.timeout || 60000,
					partSize: self.partSize || 1048576,
					parallel: self.parallel || 5,
					retryCount: self.retryCount || 3,
					retryDuration: self.retryDuration || 2,
					region: self.region,
					userId: self.userId,
					updateVideoTitle:self.liveBroadcastName,
					// 添加文件成功
					addFileSuccess: function(uploadInfo) {
						self.uploadDisabled = false
						self.resumeDisabled = false
						self.statusText = '添加文件成功, 等待上传...'
						console.log("addFileSuccess: " + uploadInfo.file.name,this.updateVideoTitle)
					},
					// 开始上传
					onUploadstarted: function(uploadInfo) {
						if(!uploadInfo.videoId) {
							let createUrl = 'http://www.h3clearning.com/huathree-back/uploadV?Title=' + this.updateVideoTitle;
							axios.get(createUrl).then(({data}) => {
								let uploadAuth = data.data.UploadAuth
								let uploadAddress = data.data.UploadAddress
								let videoId = data.data.VideoId
								uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
							})
							self.statusText = '文件开始上传...'
							console.log("onUploadStarted:" + this.updateVideoTitle + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
						} else {
							let refreshUrl = 'http://www.h3clearning.com/huathree-back/uploadV?Title=' + uploadInfo.videoId;
							axios.get(refreshUrl).then(({data}) => {
								let uploadAuth = data.data.UploadAuth
								let uploadAddress = data.data.UploadAddress
								let videoId = data.data.VideoId
								uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
							})
						}
					},
					// 文件上传成功
					onUploadSucceed: function(uploadInfo) {
						console.log("-------->"+uploadInfo+"onUploadSucceed: " + this.updateVideoTitle + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
						console.log('++++++++++++++++++'+uploadInfo.videoId);
						self.statusText = '文件上传成功!';
						self.aliyunVideoId= uploadInfo.videoId;
					},
					// 文件上传失败
					onUploadFailed: function(uploadInfo, code, message) {
						//console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
						self.statusText = '文件上传失败!'
					},
					// 取消文件上传
					onUploadCanceled: function(uploadInfo, code, message) {
						//console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
						self.statusText = '文件已暂停上传'
					},
					// 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
					onUploadProgress: function(uploadInfo, totalSize, progress) {
						console.log("onUploadProgress:file:" +  this.updateVideoTitle + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
						let progressPercent = Math.ceil(progress * 100)
						self.authProgress = progressPercent
						self.statusText = '文件上传中...'
					},
					// 上传凭证超时
					onUploadTokenExpired: function(uploadInfo) {
						let refreshUrl = 'http://www.h3clearning.com/huathree-back/refreshVideo?VideoId=' + uploadInfo.videoId;
						axios.get(refreshUrl).then(({data}) => {
							let uploadAuth = data.data.UploadAuth
							uploader.resumeUploadWithAuth(uploadAuth)
							//console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
						})
						self.statusText = '文件超时...'
					},
					// 全部文件上传结束
					onUploadEnd: function(uploadInfo) {
						//console.log("onUploadEnd: uploaded all the files")
						self.statusText = '文件上传完毕'
					}
				}) 
				return uploader;
			}
		},
		components:{
			alert,
			deleteAlert
		},
		mounted: function() {
			this.getParams();
			if(this.liveId==null||this.updateTitle==null){
				this.$store.commit('GET_LIVE_COLUMN');
				var s =this.$store.state.liveColumn;
				this.liveId=s.liveId;
				this.liveType = s.liveType;
				this.updateTitle=s.updateTitle;
				this.pathKey=s.pathKey;
				this.teacherTitle = s.teacherTitle;
				this.lecturerid = s.lecturerid 
			}
			this.getTableList();
			this.liveColumn = this.$root.huasan.liveColumn;
			window.addEventListener("beforeunload",()=>{
				s={
					liveId : this.liveId,
					liveType:this.liveType,
					updateTitle:this.updateTitle,
					pathKey:this.pathKey,
					teacherTitle:this.teacherTitle,
					lecturerid:this.lecturerid 
				}	
				this.$store.commit('SET_LIVE_COLUMN', s);
			});
		}
	}
</script>

<style>
	.liveColumn .liveSeen_inner{width: 485px!important;}
	.liveColumn .fenleiDiv .line input{width:320px!important}
</style>